package cate.game.server.configuration.dao.game;

import cate.game.db.mongo.kv.KvDao;
import cate.game.db.mongo.kv.KvMongo;
import cate.game.server.configuration.dao.MgStrKeyDao;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.model.Filters;
import easy.mongo.anno.MgMapField;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

@Slf4j
public class MgKvDao extends MgStrKeyDao<KvMongo> implements KvDao {

    @Override
    protected <S extends KvMongo> Object transId(S entity) {
        return entity.key;
    }

    @Override
    public <T extends KvMongo> List<T> findByKeyPrefix(String keyPrefix, Class<T> eleClz) {
        List<T> list = new ArrayList<>();
        Pattern pattern = Pattern.compile("^"+keyPrefix+"");
        MongoCursor<Document> iter = collection.find(Filters.eq(MgMapField.ID, pattern)).iterator();
        while (iter.hasNext()) {
            Document doc = iter.next();
            //log.info("findByKeyPrefix doc={}", doc);
            try {
                T v = (T)getMapper().decode(doc);
                list.add(v);
            } catch (Exception e) {
                log.error("", e);
            }
        }
        return list;
    }
}